<?php
declare (strict_types=1);

namespace app\circle\model\admin;

use app\common\logic\Attach as AttachLogic;
use app\common\model\Attach;
use app\common\model\BaseModel;
use app\user\model\user\Account as User;
use think\model\concern\SoftDelete;

/**
 * Class Circle
 *
 * @package app\circle\model\admin
 */
class Circle extends BaseModel
{
    use SoftDelete;

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'circle';

    /**
     * 时间显示格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';

    /**
     * 全局查询范围
     *
     * @var [type]
     */
    protected $globalScope = ['mhm'];

    /**
     * 限制机构条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     *
     * @param    [type]                         $query [description]
     */
    public function scopeMhm($query)
    {
        $query->where('mhm_id', request()->mhm_id);
    }

    /**
     * 文章类型
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/8/28
     *
     * @param $value
     * @param $data
     * @return string
     */
    public function getTypeTextAttr($value, $data)
    {
        $text = [
            1 => '自主发布',
            2 => '转载发布'
        ];

        return $text[$data['type']] ?? '未知';
    }

    /**
     * 用户信息
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/8/28
     *
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id')->with(['avatarUrl'])->bind(['avatar_url', 'nick_name']);
    }

    /**
     * 附件url获取器
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param string $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function getAttachUrlAttr($value = '', $data)
    {
        $url = [];
        if (!isset($data['attach']) || !$data['attach']) return $url;
        $attach = json_decode($data['attach'], true);
        if (!count($attach)) return $url;
        if (is_array($attach)) {
            foreach ($attach as $id) {
                $attach = Attach::find($id);
                if ($attach) {
                    if (app(AttachLogic::class)->isAudioOrVideo($attach)) {
                        $urls  = array_column($attach->fileurl, null, 'definition');
                        $url[] = $urls['OD']['play_url'];
                    } else {
                        $url[] = $attach->fileurl ?? '';
                    }
                } else {
                    $url[] = '';
                }
            }
        }

        return $url;
    }

}